package com.exsun.ex1077.ui.activity.search

import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivitySearchBinding
import com.exsun.ex1077.model.Device
import com.exsun.ex1077.network.entity.MapSearch
import com.google.android.flexbox.FlexboxLayoutManager
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.extend.view.afterTextChange
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.getCacheList
import com.zhangping.fastjetpack.extend.putCache
import com.zhangping.fastjetpack.extend.showToast
import com.zhangping.fastjetpack.extend.toColorRes
import com.zhangping.fastjetpack.extend.view.textString
import com.zhangping.fastjetpack.model.KeyValue
import com.zhangping.fastjetpack.utils.FunctionQueue
import kotlinx.android.synthetic.main.activity_search.*

/**
 * 描述：搜索
 * 作者：ZhangPing
 * 创建时间：2022/8/9 10:28
 */
class SearchActivity : BaseActivity<SearchViewModel, ActivitySearchBinding>(){

    override fun title() = "搜索"

    private val maxHistoryNum = 10

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mViewModel.pageType.set(intent.getIntExtra("pageType", Constant.SEARCH_TYPE_MAP))
        mViewModel.companyId = intent.getStringExtra("companyId") ?: ""
        mViewModel.objectType = intent.getIntExtra("objectTye", 0)
        super.initView(savedInstanceState)
        //初始化搜索历史列表和搜索结果列表
        historyListView.layoutManager = FlexboxLayoutManager(this)
        when(mViewModel.pageType.get()){
            Constant.SEARCH_TYPE_MAP -> {
                //地图搜索
                edit.hint = "请输入设备名称、设备号"
                cancel.text = "取消"
                historyListView.setup {
                    addType<MapSearch>(R.layout.list_item_search_history)
                    onClick(R.id.itemRoot){
                        selectVehicle(getModel())
                    }
                }.models = getCacheList<MapSearch>("mapSearchHistory")
                resultListView.linear().divider {
                    setDivider(1, true)
                    setColor(R.color.divider.toColorRes())
                }.setup {
                    addType<MapSearch>(R.layout.list_item_search_result)
                    onClick(R.id.itemRoot){
                        selectVehicle(getModel())
                    }
                }
            }
            else -> {
                //设备管理车牌搜索
                if (mViewModel.pageType.get() == Constant.SEARCH_TYPE_DEVICE_OBJECT){
                    edit.hint = "请输入关键字"
                }else if (mViewModel.pageType.get() == Constant.SEARCH_TYPE_DEVICE_PERSON){
                    edit.hint = "请输入负责人姓名"
                }
                cancel.text = "新增"
                resultListView.linear().divider {
                    setDivider(1, true)
                    setColor(R.color.divider.toColorRes())
                }.setup {
                    if (mViewModel.pageType.get() == Constant.SEARCH_TYPE_DEVICE_OBJECT){
                        addType<Device>(R.layout.item_device_vehicle_no_search)
                    }else if (mViewModel.pageType.get() == Constant.SEARCH_TYPE_DEVICE_PERSON){
                        addType<Device>(R.layout.item_device_person_search)
                    }
                    onClick(R.id.itemRoot){
                        val model = getModel<Device>()
                        setResult(RESULT_OK, Intent().apply {
                            putExtra("model", model)
                        })
                        finish()
                    }
                }
            }
        }

        edit.afterTextChange {
            mViewModel.searchWord.set(it)
            if (it.isEmpty()){
                resultListView.models = emptyList()
            }else{
                FunctionQueue.addFunction { mViewModel.loadData() }
            }
        }

        edit.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                mViewModel.loadData()
            }
            return@OnEditorActionListener true
        })

        delete.setOnClickListener {
            edit.setText("")
            mViewModel.searchWord.set("")
            resultListView.models = emptyList()
        }

        cancel.setOnClickListener {
            val searchWord = mViewModel.searchWord.get()
            when(mViewModel.pageType.get()) {
                Constant.SEARCH_TYPE_MAP -> {
                    //地图搜索
                    finish()
                }
                Constant.SEARCH_TYPE_DEVICE_OBJECT -> {
                    //设备管理对象名称新增
                    if (searchWord.isEmpty()){
                        "请输入要新增的车牌号".showToast()
                        return@setOnClickListener
                    }
                    if (mViewModel.objectType == Constant.OBJECT_TYPE_PERSON){
                        addAndReturn(Device().apply {
                            numberPlate = searchWord
                        })
                        return@setOnClickListener
                    }
                    mViewModel.objectNameCheck().observe(this){
                        if (it) addAndReturn(Device().apply {
                            numberPlate = searchWord
                        })
                    }
                }
                Constant.SEARCH_TYPE_DEVICE_PERSON -> {
                    //设备管理负责人新增
                    if (searchWord.isEmpty()){
                        "请输入要新增的负责人姓名".showToast()
                        return@setOnClickListener
                    }
                    addAndReturn(Device().apply {
                        name = searchWord
                    })
                }
            }
        }
    }

    /**
     * 新增并返回
     */
    private fun addAndReturn(device: Device){
        setResult(RESULT_OK, Intent().putExtra("model", device))
        finish()
    }

    private fun selectVehicle(model: MapSearch){
        //更新搜索历史列表
        var list = getCacheList<MapSearch>("mapSearchHistory")
        list.removeAll { it.number_plate == model.number_plate }
        if (list.size >= maxHistoryNum){
            list = list.subList(0, maxHistoryNum - 1)
        }
        list.add(0, model)
        "mapSearchHistory".putCache(list)
        setResult(RESULT_OK, Intent().apply {
            putExtra("dvo", model.dvo)
            putExtra("vehicleNo", model.number_plate)
        })
        finish()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.apply {
            mapSearchResult.observe(this@SearchActivity){
                parseState(it, {
                    resultListView.models = it
                })
                FunctionQueue.executeNext()
            }
            vehicleNoSearchResult.observe(this@SearchActivity){
                parseState(it, {
                    resultListView.models = it
                })
                FunctionQueue.executeNext()
            }
            personSearchResult.observe(this@SearchActivity){
                parseState(it, {
                    resultListView.models = it
                })
                FunctionQueue.executeNext()
            }
        }
    }

}